import React, { useState, useEffect, useCallback, } from 'react'
import { Col, Form, Input, Button, Table, Modal, message, Select, DatePicker, Radio, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import MemberTreeSelect from './components/memberTree'
import GroupTree from './components/groupTree'
import {
  fetchMembers,
  addMembers,
  delMembers,
  editMembers,
} from '@/services/setting/member'
import {
  fetchGroupTree,
} from '@/services/group'
import { formItemLayout } from '@/utils/utils'
import { connect } from 'dva'
import moment from 'moment'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const columns = [
  {
    title: '编号',
    dataIndex: 'number',
    key: 'number',
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '职位名称',
    dataIndex: 'positionName',
    key: 'positionName',
  },
  {
    title: '组织名称',
    dataIndex: 'groupName',
    key: 'groupName',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '生日',
    dataIndex: 'birthday',
    key: 'birthday',
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex',
    render: t => <>{t == 1 ? '男' : t == 2 ? '女' : null}</>
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '婚否',
    dataIndex: 'married',
    key: 'married',
    render: t => <>{t == 1 ? '是' : t == 0 ? '否' : null}</>
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
]

const Members = props => {
  const { form, role, dispatch, } = props
  const { inform, userList, manages, } = role
  const { getFieldDecorator } = form
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState({})
  const [treeData, setTreeData] = useState([])
  const [groupId, setGroupId] = useState(null)
  const [visible, setVisible] = useState(false)
  const [modalTreeKey, setModalTreeKey] = useState(null)
  const [btnType, setBtnType] = useState(null)

  useEffect(() => {
    getGroupTree()
    init()
    dispatch({
      type: 'role/fetchUsers'
    })
    dispatch({
      type: 'role/fetchManageList'
    })
  }, [])

  const init = useCallback(async params => {
    const r = await fetchMembers(params);
    setColData(r.data);    
  }, []);
  
  const getGroupTree = async (params = { supplierType: 1 }) => {
    const res = await fetchGroupTree(params)
    setTreeData(res.data)
  }

  const editData = async params => {
    const res = await editMembers(params)
    message.info(res.msg) && init()
  }

  const addData = async params => {
    const res = await addMembers(params)
    message.info(res.msg) && init()
  }

  const handleMember = e => {
    e.preventDefault
    form.validateFields((err, values) => {
      if (!err) {
        btnType == 3 ?
        editData({
          ...inform,
          ...values,
          birthday: values.birthday && moment(values.birthday).format('YYYY-MM-DD'),
          groupId: modalTreeKey[0],
        }) :
        addData({
          ...values,
          groupId: modalTreeKey[0],
          birthday: values.birthday && moment(values.birthday).format('YYYY-MM-DD'),
        })
        setVisible(!visible)
      }
    })
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      // 处理表单数据
      let params = {}
      Object.keys(values)
        .filter(v => /^f.+?/.test(v))
        .map(p => 
          params[p.substring(1)] = values[p]
        )
      init({
        ...params,
        groupId,
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
    init()
  }
  // 查询条件
  const getFields = () => {
    return(
      <>
        <Col span={8}>
          <Form.Item label={`组织机构`}>
            <MemberTreeSelect 
              data={treeData} 
              onSelect={value => setGroupId(value)}
            />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="职位">
            {getFieldDecorator('fpositionId', {
            })(
              <Select>
                {
                  manages.map(n => 
                    <Option key={n.id} value={n.id} >{n.name}</Option>
                )}
              </Select>
            )}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="名称">
            {getFieldDecorator('fname', {
            })(
              <Input />
            )}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="手机号">
            {getFieldDecorator('fphone', {
            })(
              <Input />
            )}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label="编号">
            {getFieldDecorator('fnumber', {
            })(
              <Input />
            )}
          </Form.Item>
        </Col>
      </>
    )
  }

  // 按钮处理
  const handleBtn = type => {
    setBtnType(type)
    if (type != 1 && record.length == 0) return message.warning('请选择一条数据')
    switch (type) {
      case 1: // add
        return handleStatus()
      case 3: // edit
        return handleStatus(record[0])
      case 4:
        return delMembers({
          id: record[0].id
        }).then(() => init())
      default:
        break;
    }
  }
  // 新增/修改 模态框
  const handleStatus = (record = {}) => {    
    setVisible(!visible);
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  }

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id}
      />
      <Modal
        visible={visible}
        onOk={handleMember}
        onCancel={() => setVisible(!visible)}
        destroyOnClose
        title='新增/删除'
      >
        <Form {...formItemLayout}>
          <Form.Item label="编号">
            {getFieldDecorator('number', {
              initialValue: inform && inform.number,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="姓名">
            {getFieldDecorator('name', {
              initialValue: inform && inform.name,
              rules: [{
                required: true,
              }]
            })(<Input />)}
          </Form.Item>
          <Form.Item label="机构组织">
            {getFieldDecorator('groupId', {
            })(<GroupTree 
              data={treeData}
              onSelect={id => setModalTreeKey(id)}  
              defaultSelectedKeys={[inform && String(inform.groupId)]}     
            />)}
          </Form.Item>
          <Form.Item label="关联用户">
            {getFieldDecorator('userId', {
              initialValue: inform && inform.userId,
              rules: [{
                required: true,
              }]
            })(<Select style={{width: 200}}>
              {userList.map(n => 
                <Option key={n.id} value={n.id} >{n.username}</Option>
            )}
          </Select>)}
          </Form.Item>
          <Form.Item label="员工类型">
            {getFieldDecorator('workType', {
              initialValue: inform && inform.workType,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="手机号">
            {getFieldDecorator('phone', {
              initialValue: inform && inform.phone,
            })(<Input />)}
          </Form.Item>
          <Form.Item label="邮箱">
            {getFieldDecorator('email', {
              initialValue: inform && inform.email,
              })(<Input />)}
          </Form.Item>
          <Form.Item label="生日">
            {getFieldDecorator('birthday', {
              initialValue: (inform && typeof inform.birthday == 'string') ?  moment(inform.birthday, 'YYYY-MM-DD') : null,
              })(<DatePicker />)}
          </Form.Item>
          <Form.Item label="性别">
            {getFieldDecorator('sex', {
              initialValue: inform && inform.sex,
              })(<Radio.Group >
                  <Radio value={'1'}>男</Radio>
                  <Radio value={'2'}>女</Radio>
                </Radio.Group>
                )}
          </Form.Item>
          <Form.Item label="地址">
            {getFieldDecorator('address', {
              initialValue: inform && inform.address,
              })(<Input />)}
          </Form.Item>
          <Form.Item label="婚否">
            {getFieldDecorator('married', {
              initialValue: inform && inform.married,
              })(<Radio.Group >
                <Radio value={'1'}>是</Radio>
                <Radio value={'0'}>否</Radio>
              </Radio.Group>)}
          </Form.Item>
          <Form.Item label="职位">
            {getFieldDecorator('positionId', {
              initialValue: inform && inform.positionId,
            })(
              <Select>
                {
                  manages.map(n => 
                    <Option key={n.id} value={n.id} >{n.name}</Option>
                )}
              </Select>
            )}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default connect(({role}) => ({
  role,
}))(Form.create()(Members))